/**
 * Created by macos on 14/11/28.
 */

var crypto = require('crypto');

(function(){

  var root = this;
  var authorization = {};

  function _encrypt(params, secret, timestamp) {

    var sort = params;

    params.push(secret);
    params.push(timestamp);
    params.sort();

    var authorization = "";
    for (var i = 0; i < params.length; i++) {
      authorization += params[i];
    }

    sails.log.debug("authorization._encrypt:authorization:", authorization);
    authorization = crypto.createHmac('sha1', secret).update(authorization).digest('base64');

    sails.log.debug("authorization._encrypt:authorization:", authorization);
    return authorization;
  }

  authorization.encrypt = function encrypt(params, secret, timestamp) {
    return _encrypt(params, secret, timestamp);
  }

  authorization.validate = function validate(authCode, params, secret, timestamp) {
    var checkAuthCode = _encrypt(params, secret, timestamp);
    return (authCode === checkAuthCode);
  }

  // Node.js
  if (typeof module !== 'undefined' && module.exports) {
    module.exports = authorization;
  }
  // AMD / RequireJS
  else if (typeof define !== 'undefined' && define.amd) {
    define([], function () {
      return authorization;
    });
  }
  // included directly via <script> tag
  else {
    root.authorization = authorization;
  }
})()
